export async function checkWritePhotosAlbumAuth() {
  return await new Promise((resolve, inject) => {
    wx.getSetting({
      success (res) {
        // res.authSetting = {
        //   "scope.writePhotosAlbum": true,
        // }
        // console.log('getSetting', res.authSetting);
        const keys = Object.keys(res.authSetting);
        if (!keys.includes('scope.writePhotosAlbum')) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success () {
              // console.log('authorize success');
              resolve(true);
            },
          });
        } else if (res.authSetting['scope.writePhotosAlbum']) {
          resolve(true);
        } else {
          wx.openSetting({
            success (res) {
              // console.log('openSetting', res.authSetting);
              if (res.authSetting['scope.writePhotosAlbum']) {
                resolve(true);
              } else {
                resolve(false);
              }
            },
            fail (error) {
              console.error('openSetting', error);
              resolve(false);
            },
          });
        }
      },
      fail (error) {
        console.error('getSetting', error);
        resolve(false);
      },
    })
  });
}

export async function saveImageToPhotosAlbum({ filePath, success, fail }) {
  const result = await checkWritePhotosAlbumAuth();
  if (!result) {
    return;
  }
  wx.saveImageToPhotosAlbum({
    filePath,
    success: () => {
      if (success) success();
    },
    fail: error => {
      if (fail) fail(error);
    }
  });
}